﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HanGu.Services.Interface;
using HanGu.Entity;
using HanGu.Common;
using System.Text;

namespace Hangu.WebClient.Controllers.Admin
{
    public class AdvertisementController : AdminBaseController
    {
        private static readonly IAdvertisement serviceActive = ServiceFactory.GetService<IAdvertisement>();
        private static readonly IModule serviceModule = ServiceFactory.GetService<IModule>();

        //
        // GET: /Advertisement/
        public ActionResult Index()
        {
            int intobj1 = 0;
            if (Session["classType"] != null)
            {
                int.TryParse(Session["classType"].ToString(), out intobj1);
            }
            SearchParma.IntObj1 = intobj1;
            return View(viewList, GetAdvertisementList());
        }

        [HttpPost]
        public ActionResult Index(FormCollection collection)
        {
            int intobj1 = 0;
            int.TryParse(Request["IntObj1"], out intobj1);
            SearchParma.IntObj1 = intobj1;
            Session["classType"] = SearchParma.IntObj1;
            SearchParma.Pagination.RowCount = null;
            return View(viewList, GetAdvertisementList());
        }

        List<Advertisement> GetAdvertisementList()
        {
            ViewData["ClassTypeList"] = GetClassType();            
            List<Advertisement> advertisementList = serviceActive.GetAll(base.SearchParma);
            ViewData["RowCount"] = SearchParma.Pagination.RowCount;
            return advertisementList;
        }
        SelectList GetClassType()
        {
            var classtype = serviceModule.GetAll();
            var singleModule = classtype.SingleOrDefault(c => c.ID == SearchParma.IntObj1);
            if (singleModule == null)
            {
                singleModule = classtype.FirstOrDefault();
            }
            if (singleModule != null)
            {
                if (SearchParma.IntObj1 != -1)
                {
                    SearchParma.IntObj1 = singleModule.ID;
                    ViewBag.XmlPath = "Xml/" + singleModule.AdXml;
                }
            }
            classtype.Add(new Module() { ID=-1, Title="右边栏位广告"});
            SelectList list = new SelectList(classtype, "ID", "Title");
            return list;
        }

        public ActionResult Create(int id)
        {
            Advertisement advertisement = new Advertisement() { CreateTime = DateTime.Now, Creator = CurentUser.UserName, UpdateTime = DateTime.Now, Updater = CurentUser.UserName };
            ViewData["ClassTypeList"] = GetClassType();
            if (id > 0)
            {
                advertisement = serviceActive.GetByID(id);
            }
            if (!advertisement.IsTitle.HasValue)
            {
                advertisement.IsTitle = false;
            }
            if (string.IsNullOrEmpty(advertisement.FilePath))
            {
                advertisement.FilePath = "/Content/default.jpg";
            }
            return View(viewCreate, advertisement);
        }

        //
        // POST: /Advertisement/Create

        [HttpPost]
        [ValidateInput(false)]
        public string Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here
                Advertisement advertisement = new Advertisement();
                TryUpdateModel(advertisement, collection);
                Session["classType"] = advertisement.ClassType;
                if (Request["IsTitle"] != null)
                {
                    advertisement.IsTitle = true;
                }
                else
                { advertisement.IsTitle = false; }

                if (Request.Files.Count > 0 && Request.Files[0].ContentLength > 0)
                {
                    if (Request.Files[0].ContentType.IndexOf("image") >= 0)
                    {
                        UploadFileManage uploadFile = new UploadFileManage(Request.Files[0]);
                        uploadFile.ClassType = navTabId;
                        uploadFile.Save();
                        if (!uploadFile.Error)
                        {
                            //先删除旧图片
                            if (!string.IsNullOrEmpty(advertisement.FilePath))
                            {
                                uploadFile.DeleteFile(advertisement.FilePath);
                            }
                            advertisement.FilePath = uploadFile.FileInfo["filepath"];
                            if (advertisement.ID > 0)
                            {
                                serviceActive.Update(advertisement);
                            }
                            else
                            {
                                serviceActive.Add(advertisement);
                            }
                        }
                        else
                        {
                            ajaxStr = string.Format(ajaxStr, 300, uploadFile.Message, navTabId, "", "");
                        }
                    }
                    else
                    { ajaxStr = string.Format(ajaxStr, 300, ResourceManager.UnusefulImag, navTabId, "", ""); }
                }
                else
                {
                    if (advertisement.ID > 0)
                    {
                        serviceActive.Update(advertisement);
                    }
                    else
                    {
                        serviceActive.Add(advertisement);
                    }

                }
                ajaxStr = string.Format(ajaxStr, 200, ResourceManager.SaveSuccess, navTabId, "", "closeCurrent");

            }
            catch (Exception ex)
            {
                base.ExceptionHand(ex);
                ajaxStr = string.Format(ajaxStr, 300, ResourceManager.SaveFail, navTabId, "", "");
            }
            return "{" + ajaxStr + "}";
        }

        //
        // GET: /Advertisement/Edit/5

        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /Advertisement/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        const string headXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><bcaster autoPlayTime=\"10\">\r\n{0}</bcaster>";
        const string itemXml = "<item item_url=\"{0}\" link=\"{1}\" itemtitle=\"{2}\"></item>\r\n";
        public string SaveXml(int id, string guid)
        {
            try
            {
                SearchParma.IntObj1 = id;
                string filepath = RijndaelSecurity.DecryptDES(guid);
                var adList = serviceActive.GetAll(base.SearchParma);
                StringBuilder xmlBuider = new StringBuilder();
                foreach (var item in adList)
                {
                    if (!item.IsTitle.HasValue || item.IsTitle.Value == false) item.Title = string.Empty;
                    xmlBuider.Append(string.Format(itemXml, item.FilePath, item.Url, item.Title));
                }
                string xml = string.Format(headXml, xmlBuider.ToString());
                //保存文件
                FileManagement.ReWriteReadinnerText(filepath, xml);
                ajaxStr = string.Format(ajaxStr, 200, ResourceManager.SaveSuccess, navTabId, "", "");

            }
            catch (Exception ex)
            {
                base.ExceptionHand(ex);
                ajaxStr = string.Format(ajaxStr, 300, ResourceManager.SaveFail, navTabId, "", "");

            }
            return "{" + ajaxStr + "}";
        }

        //
        // GET: /Advertisement/Delete/5
        [HttpPost]
        public string Delete(int id, string guid)
        {
            try
            {
                try
                {
                    FileManageController filemanage = new FileManageController();
                    filemanage.DeleteExecute(guid);
                }
                catch { }
                serviceActive.Delete(id);
                ajaxStr = string.Format(ajaxStr, 200, ResourceManager.DeleteSuccess, navTabId, "", "");
            }
            catch (Exception ex)
            {
                ExceptionHand(ex);
                ajaxStr = string.Format(ajaxStr, 300, ResourceManager.DeleteFail, navTabId, "", "");
            }

            return "{" + ajaxStr + "}";

        }
    }
}
